<template>
  <div class="login">
    <div class="content">
      <div class="left">
        <img class="logo" src="../../assets/images/logo_login.png" alt="" />
        <span class="lineBox"></span>
        <span class="logo_title">运维管理后台</span>
      </div>
      <div class="right">
        <div class="title">用户登录</div>
        <el-form class="form" :model="loginData" label-position="left">
          <div class="topWrapper">
            <div>
              <div class="list">
                <el-form-item>
                  <el-input
                    v-model.trim="loginData.loginName"
                    placeholder="账号"
                    clearable
                  >
                    <template #suffix>
                      <img src="../../assets/images/login_user.png" alt="" />
                    </template>
                  </el-input>
                </el-form-item>
              </div>
              <div class="list">
                <el-form-item>
                  <el-input
                    type="password"
                    v-model.trim="loginData.loginPwd"
                    placeholder="密码"
                    clearable
                  >
                    <template #suffix>
                      <img
                        src="../../assets/images/login_password.png"
                        alt=""
                      />
                    </template>
                  </el-input>
                </el-form-item>
              </div>
              <div class="list">
                <el-form-item class="item_flex">
                  <el-input
                    v-model.trim="loginData.picCaptcha"
                    placeholder="请输入验证码（不区分大小写）"
                    clearable
                  ></el-input>
                  <div class="identifying_code">
                    <img :src="imgSrc" alt="" @click="get_picCaptcha" />
                  </div>
                </el-form-item>
              </div>
            </div>
          </div>
        </el-form>
        <div class="remember">
          <!-- <img src="../../assets/images/login_checkbox.png" alt="" v-if="!checked" @click="changeChecked">
          <img src="../../assets/images/checkbox_checked.png" alt="" v-else @click="changeChecked"> -->
          <el-checkbox
            v-model="checked"
            label=""
            size="large"
            @change="changeChecked"
          />
          <span>记住账号密码</span>
        </div>
        <div class="btn">
          <el-button type="warning" @click="toLogin">登 录</el-button>
        </div>
        <div class="forget">
          <span @click="forgetPassword">忘记密码</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive } from "vue";
import {
  authLogin,
  loginWithPic,
  getDetailByLogin,
  queryMenuTree,
  getUserProject,
  getPicCaptcha,
} from "../../http/user";
import { useMain, store } from "../../store/index";
import { getOptions, setTopics, setTopics2 } from "@/utils/mqttConfig.js";
import main from "../../main";
import * as mqtt from "mqtt/dist/mqtt.min";
import { userMsgCount } from "@/http/message";
import { qzsList } from "@/utils/menuList";
import { getCookie, filterMenuData, getenv, getMqttUrl } from "@/utils/utils";
import { storeToRefs } from "pinia";
import CryptoJS from "crypto-js";

const router = useRouter();

const useMainStore = useMain(store); //pinia
let { userInfo, environmentInfo } = storeToRefs(useMainStore);

const loginData = reactive({
  loginName: "", //账户名
  loginPwd: "", //密码
  picCaptcha: "", //图片验证码
});

let imgSrc = ref("");

let isWatching = ref(false); //是否开启监听

//监听账号变化,如果跟缓存一样,自动补上密码,否则清空密码
watch(
  () => loginData.loginName,
  (newVal, oldVal) => {
    if (isWatching.value) {
      let loginInfo = localStorage.getItem("loginData");
      if (newVal && loginInfo && newVal == JSON.parse(loginInfo).loginName) {
        loginData.loginPwd = JSON.parse(loginInfo).loginPwd;
      } else {
        loginData.loginPwd = "";
      }
    }
  }
);

const checked = ref(false); //是否勾选了记住密码

//获取之前记住的账号密码
onMounted(() => {
  console.log("getMqttUrl", getMqttUrl());

  let loginInfo = localStorage.getItem("loginData");
  if (loginInfo) {
    loginData.loginName = JSON.parse(loginInfo).loginName;
    loginData.loginPwd = JSON.parse(loginInfo).loginPwd;
    checked.value = true;
  }
  //开启账号变化监听
  nextTick(() => {
    isWatching.value = true;
  });

  let authToken = getCookie("authToken");
  let refreshToken = getCookie("refreshToken");
  console.log("authToken", authToken);
  console.log("refreshToken", refreshToken);
  //如果localStorage中存在token,获取用户项目信息
  if (authToken && refreshToken) {
    useMainStore.updatedAuthToken(authToken);
    useMainStore.updatedRefreshToken(refreshToken);
    setTimeout(() => {
      getUserProjectInfo();
    }, 100);
  }
});

//点击复选框
const changeChecked = () => {
  // checked.value = !checked.value;
};

let userId = ref(""); //用户id
let platformType = ref(0); //平台类型
let projectId = ref(""); //项目id

let token = reactive({
  authToken: "",
  refreshToken: "",
});

//点击登录
const toLogin = () => {
  // router.push('/home');
  // return;
  if (!loginData.loginName) {
    ElMessage({
      message: "请输入登录账号!",
      type: "warning",
    });
    return;
  }
  if (!loginData.loginPwd) {
    ElMessage({
      message: "请输入登录密码!",
      type: "warning",
    });
    return;
  }
  if (!loginData.picCaptcha) {
    ElMessage({
      message: "请输入图形验证码!",
      type: "warning",
      offset: document.getElementsByTagName("body")[0].offsetHeight / 2 - 24,
    });
    return;
  }
  const key = CryptoJS.enc.Base64.parse(
    "6Lrf4OiK/ARcyaSRXwB2FixvgHSYuN8XKBhccF4F+PY="
  );
  let loginName = CryptoJS.AES.encrypt(
    CryptoJS.enc.Utf8.parse(loginData.loginName),
    key,
    {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    }
  );
  let loginPwd = CryptoJS.AES.encrypt(
    CryptoJS.enc.Utf8.parse(loginData.loginPwd),
    key,
    {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    }
  );
  let picCaptcha = CryptoJS.AES.encrypt(
    CryptoJS.enc.Utf8.parse(loginData.picCaptcha),
    key,
    {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    }
  );
  let params = {
    loginName: loginName.toString(), //账户名
    loginPwd: loginPwd.toString(), //账户名
    picCaptcha: picCaptcha.toString(), //账户名
  };
  loginWithPic(params)
    .then((res: any) => {
      // loginWithPic(loginData).then((res: any) => {
      // authLogin(loginData).then((res: any) => {
      if (res.result && res.result.authToken && res.result.refreshToken) {
        token.authToken = res.result.authToken;
        token.refreshToken = res.result.refreshToken;
        useMainStore.updatedAuthToken(res.result.authToken);
        useMainStore.updatedRefreshToken(res.result.refreshToken);
        useMainStore.updatedUserProjectRsps(res.result.userProjectRsps); //项目信息
        //项目id
        if (
          res.result.userProjectRsps &&
          res.result.userProjectRsps.length > 0
        ) {
          projectId.value = res.result.userProjectRsps[0].projectId;
          useMainStore.updatedProjectInfo(res.result.userProjectRsps[0]);
        } else {
          useMainStore.updatedProjectInfo({});
        }

        if (checked.value) {
          localStorage.setItem("loginData", JSON.stringify(loginData));
        } else {
          localStorage.removeItem("loginData");
        }
        // router.push('/home');
        getUserInfo(); //获取用户信息
        getMsgNum(); //获取消息数
      } else {
        get_picCaptcha();
      }
    })
    .catch(() => {
      get_picCaptcha();
    });
};

//获取用户信息
const getUserInfo = () => {
  getDetailByLogin().then((res: any) => {
    if (res.result) {
      userId.value = res.result.id;

      useMainStore.updatedUserInfo(res.result);

      //用户类型为超级管理员或平台管理员时,存储token信息到cookie中
      if (
        token.authToken &&
        token.refreshToken &&
        (res.result.type == 0 ||
          res.result.type == 1 ||
          res.result.type == 3 ||
          res.result.type == 4)
      ) {
        var date = new Date();
        // 将日期增加一天，得到明天的日期对象
        // date.setTime(date.getTime() + 24 * 60 * 60 * 1000);
        date.setDate(date.getDate() + 1);
        document.cookie =
          "authToken=" +
          token.authToken +
          "; domain=" +
          import.meta.env.VITE_TARGET_URL +
          "; expires=" +
          date.toUTCString() +
          "; path=/";
        document.cookie =
          "refreshToken=" +
          token.refreshToken +
          "; domain=" +
          import.meta.env.VITE_TARGET_URL +
          "; expires=" +
          date.toUTCString() +
          "; path=/";
        document.cookie =
          "useType=" +
          res.result.type +
          ";domain=" +
          import.meta.env.VITE_TARGET_URL +
          "; expires=" +
          date.toUTCString() +
          "; path=/";
      }

      // router.push('/home');

      getMenuTree(); //获取用户资源
    }
  });
};

//获取用户资源
const getMenuTree = () => {
  let params = {
    platformTypes: [3] + "",
  };
  queryMenuTree(params).then(async (res: any) => {
    if (res && res.result) {
      if (res.result && res.result.length > 0 && res.result[0].children) {
        // let data = JSON.parse(JSON.stringify(res.result[0].children));
        let data = res.result[0].children;
        filterMenuData(data);
        // useMainStore.updatedMenuListInfo(data);//菜单列表存储到pina中

        // let data_new = data.concat(qzsList);
        let data_new: any = qzsList;
        useMainStore.updatedMenuListInfo(data_new); //菜单列表存储到pina中
      } else {
        useMainStore.updatedMenuListInfo([]); //菜单列表存储到pina中
      }
      await getenv((res_env: any) => {
        let environmentInfo = res_env.result ? res_env.result : "";
        useMainStore.updatedEnvironmentInfo(environmentInfo); //环境信息存储到pina中
      });
      //跳转第一个有pageUrl的路由
      if (
        res.result.length > 0 &&
        res.result[0] &&
        res.result[0].children &&
        res.result[0].children.length > 0
      ) {
        platformType.value = res.result[0].platformType; //平台类型
        //连接mqtt
        // main.config.globalProperties.$mqtt = mqtt.connect(import.meta.env.VITE_MQTT_URL, getOptions())
        let mqtt_url = getMqttUrl();
        main.config.globalProperties.$mqtt = mqtt.connect(
          mqtt_url,
          getOptions()
        );
        //设置订阅主题(总平台系统公告)
        setTopics(platformType.value, projectId.value, userId.value);
        //设置订阅主题(运维平台通知公告)
        setTopics2(projectId.value, userId.value);
        //启动mqtt状态监听
        useMainStore.mqtt_service();

        // if (res.result[0].children[0].pageUrl) {
        //   router.push(res.result[0].children[0].pageUrl);
        // } else {
        //   router.push(res.result[0].children[0].children[0].pageUrl);
        // }
        router.push("/integratedServices/schedulingManage");
      } else {
        router.push("/noPermission");
      }
    }
  });
};

//获取消息数
const getMsgNum = () => {
  userMsgCount().then((res: any) => {
    if (res.result) {
      let msgNum =
        Number(res.result.alarmMsgCount) + Number(res.result.noticeCount);
      useMainStore.updatedMsgNum(msgNum); //消息数存储到pina中
    }
  });
};

//跳转忘记密码页面
const forgetPassword = () => {
  router.push("/forgetPassword");
};

//获取项目信息
const getUserProjectInfo = () => {
  getUserProject().then((res: any) => {
    if (res && res.result) {
      useMainStore.updatedUserProjectRsps(res.result); //项目信息
      //项目id
      if (res.result && res.result.length > 0) {
        projectId.value = res.result[0].projectId;
        useMainStore.updatedProjectInfo(res.result[0]);
      } else {
        useMainStore.updatedProjectInfo({});
      }
    }
    getUserInfo(); //获取用户信息
    getMsgNum(); //获取消息数
  });
};

//获取图形验证码
const get_picCaptcha = () => {
  getPicCaptcha().then((res: any) => {
    imgSrc.value = window.URL.createObjectURL(res);
  });
};
get_picCaptcha();
</script>

<style lang="scss">
.login {
  width: 100%;
  height: 100%;
  position: relative;
  background: rgba(0, 0, 0, 1);

  .content {
    width: 100%;
    height: 590px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    background: url(../../assets/images/login_bg.jpg) no-repeat;
    background-size: 100% 100%;
    // padding-top: 67px;
    padding-top: 20px;
    padding-right: 11.97%;
    padding-left: 18.12%;
    display: flex;

    .left {
      flex: 1;
      // padding-top: 171px;
      padding-top: 218px;
      display: flex;

      .logo {
        width: 110px;
        height: 129px;
      }

      .lineBox {
        width: 3px;
        height: 50px;
        background: rgba(248, 221, 142, 1);
        margin: 50px 36px 0;
      }

      .logo_title {
        font-size: 30px;
        font-weight: 400;
        letter-spacing: 2px;
        line-height: 36.31px;
        color: rgba(192, 164, 91, 1);
        margin-top: 55px;
      }
    }

    .right {
      // width: 425px;
      width: 485px;
      // height: 470px;
      height: 550px;
      background: url(../../assets/images/login_box.png) no-repeat;
      background-size: 100% 100%;
      padding: 32px 50px 28px 50px;

      .title {
        font-size: 24px;
        font-weight: 400;
        letter-spacing: 0px;
        line-height: 30px;
        color: rgba(192, 164, 91, 1);
        text-align: center;
        vertical-align: top;
        margin-bottom: 33px;
      }

      .topWrapper {
        width: 100%;

        .list {
          &:nth-child(2) {
            margin: 20px 0 0 0;
          }

          &:last-child {
            margin: 20px 0 50px 0;
          }

          .el-form-item {
            width: 100%;
            margin-bottom: 0;

            .el-input {
              width: 100%;
              height: 60px;
              line-height: 60px;
              background: url(../../assets/images/login_input_bg.png) no-repeat;
              background-size: 100% 100%;

              .el-input__wrapper {
                background: rgba(112, 105, 95, 0.2);
                box-shadow: none;
                padding-left: 23px;

                .el-input__inner {
                  font-size: 16px;
                  font-weight: 400;
                  letter-spacing: 0px;
                  line-height: 35px;
                  color: rgba(192, 164, 91, 1);

                  &::placeholder {
                    font-size: 16px;
                    font-weight: 400;
                    letter-spacing: 0px;
                    line-height: 35px;
                    color: rgba(192, 164, 91, 1);
                  }
                }
              }

              .el-input__suffix {
                height: auto;
                font-size: 20px;
                // width: 60px;

                .el-input__suffix-inner {
                  width: 100%;
                  flex-direction: row-reverse;
                  -webkit-flex-direction: row-reverse;
                  justify-content: flex-end;
                  display: flex;

                  .el-input__clear {
                    font-size: 15px;
                    color: rgba(112, 105, 95);
                    margin-right: 20px;
                  }
                }
              }
            }

            &.item_flex {
              display: flex;

              .getCode {
                width: 100px;
                height: 30px;
                border-radius: 5px;
                background: rgba(192, 164, 91, 1);
                box-shadow: 0px 2px 7px 0px rgba(169, 143, 84, 0.25);
                font-size: 14px;
                font-weight: 400;
                letter-spacing: 0px;
                line-height: 30px;
                text-align: center;
                color: rgba(255, 255, 255, 1);
                cursor: pointer;
                margin-left: 16px;
              }

              .identifying_code {
                width: 125px;
                height: 60px;
                background-color: #fff;

                img {
                  width: 100%;
                  height: 100%;
                  cursor: pointer;
                }
              }

              .el-input {
                flex: 1;
              }
            }
          }
        }
      }

      .remember {
        display: flex;
        align-items: center;
        font-size: 13px;
        font-weight: 400;
        letter-spacing: 1px;
        line-height: 35px;
        color: rgba(114, 114, 114, 1);
        margin-bottom: 17px;

        // img {
        //   width: 20px;
        //   height: 20px;
        //   margin-right: 20px;

        //   vertical-align: text-top;
        // }
        .el-checkbox {
          margin-right: 20px;

          .el-checkbox__inner {
            width: 16px;
          }
        }
      }

      .btn {
        .el-button {
          width: 100%;
          height: 50px;
          font-size: 16px;
          font-weight: 400;
          letter-spacing: 0px;
          line-height: 50px;
          color: rgba(255, 255, 255, 1);
        }
      }

      .forget {
        margin-top: 20px;
        text-align: center;

        span {
          font-size: 13px;
          font-weight: 400;
          letter-spacing: 1px;
          line-height: 35px;
          color: rgba(114, 114, 114, 1);
          cursor: pointer;
        }
      }
    }
  }
}
</style>
